<?php

namespace app\admin\controller\wx;

use app\common\controller\Backend;
use think\exception\DbException;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Wxorderinfo extends Backend
{
    
    /**
     * Wxorderinfo模型对象
     * @var \app\admin\model\Wxorderinfo
     */
    protected $model = null;
    protected $modelOrder = null;
    protected $Wxproduct = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Wxorderinfo;
        $this->modelOrder = new \app\admin\model\Wxorder;
        $wxproduct = new \app\admin\model\Wxproduct();
        $list = collection($wxproduct->select())->toArray();
        $this->Wxproduct =array_column($list,'name','id');
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index($ids = null)
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['wxorder'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['wxorder'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','order_id','order_sn','wxproduct_id','kg','price','dk']);
                $row->visible(['wxorder']);
				$row->getRelation('wxorder')->visible(['receipt','phone','address']);
            }
            $list = collection($list)->toArray();
            foreach ($list as &$value)
            {
                $value['wxproduct_id'] = $this->Wxproduct[$value['wxproduct_id']];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        if($ids > 0)
        {
            $rowData = $this->modelOrder->get($ids);
            $this->view->assign('order_sn',$rowData['order_sn']);
        }else{
            $this->view->assign('order_sn',0);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add($ids= null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $params['order_sn'] = $ids;
                    $wxproduct = new \app\admin\model\Wxproduct();
                    $wxproductRow = $wxproduct->get($params['wxproduct_id']);
                    $params['kg'] = $wxproductRow->kg;
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->orderUp($ids);
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);

        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $wxproduct = new \app\admin\model\Wxproduct();
                    $wxproductRow = $wxproduct->get($row->wxproduct_id);
                    $params['kg'] = $wxproductRow->kg;
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->orderUp($row->order_sn);
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            $order_sn = [];
            foreach ($list as $k => $v) {
                $order_sn[] = $v['order_sn'];
                $count += $v->delete();
            }
            if ($count) {
                foreach ($order_sn as $value)
                {
                    $this->orderUp($value);
                }
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    protected function orderUp($order_sn)
    {
        //获取订单详情统计重量 (价格待确定)
        $order = new \app\admin\model\Wxorder();
        try {
            $row = $order->get(['order_sn' => $order_sn]);
            $row->akg = $this->model->where('order_sn',$order_sn)->sum('kg');
            $row->amount = $this->model->where('order_sn',$order_sn)->sum('price');
            $row->save();

            //企业微信通知

        } catch (DbException $e) {
            $this->error('错误代码：10090');
        }

    }


    public function info()
    {
        $list = $this->model
            ->alias('a')
            ->join('hdyj_wxorder b','a.order_sn = b.order_sn')
            ->where('b.status =0 or b.status =1 or b.status=3')
            ->where('b.state =0')
            ->field('a.id,sum(a.num) as num,a.goods_name')->group('a.wxproduct_id')->select();
        $this->view->assign('list',$list);
        return $this->view->fetch();
    }
}
